<template>
  <NavBar
    :title="title"
    :leftArrow="false" />
  <div class="features">
    <div
      class="item"
      @click="onFeatureClick('identify')">
      植物识别
      <image
        src="../../static/icon/花，植物.svg"
        mode="scaleToFill" />
    </div>
    <div
      class="item"
      @click="onFeatureClick('record')">
      开始记录
      <image
        src="../../static/icon/成长.svg"
        mode="scaleToFill" />
    </div>
    <div
      class="item"
      @click="onFeatureClick('history')">
      识别历史
      <image
        src="../../static/icon/硬盘，存储，空间.svg"
        mode="scaleToFill" />
    </div>
  </div>

  <van-action-sheet
    :show="showActionSheet"
    :actions="actionSheet"
    @select="onActionSheetSelect"
    @close="closeActionSheet" />
</template>

<script>
import NavBar from "../../components/NavBar/NavBar.vue";
import { addPlant, addRecognizeRecord } from "../../api/plant";
import { recognize } from "../../api/recognize";
import { globalParams } from "../../../public/config.js";
import { mapState, mapMutations } from "vuex";

export default {
  components: {
    NavBar,
  },
  computed: {
    ...mapState(["recognizeData", "userInfo"]),
  },
  data() {
    return {
      text: "hello",
      title: "识别",
      showActionSheet: false,
      actionSheet: [],
      recognizeActionSheet: [
        {
          name: "拍摄",
        },
        {
          name: "相册",
        },
      ],
      recordActionSheet: [
        {
          name: "写入记录",
        },
        {
          name: "读取记录",
        },
      ],
      fileList: [],
      imgData: {},
      globalParams,
    };
  },
  methods: {
    ...mapMutations(["setRecognizeData"]),

    // 点击功能按钮
    onFeatureClick(feature) {
      console.log(feature);
      if (feature === "identify") {
        this.actionSheet = this.recognizeActionSheet;
        this.showActionSheet = true;
      } else if (feature === "record") {
        this.actionSheet = this.recordActionSheet;
        this.showActionSheet = true;
      } else if (feature === "history") {
        // 跳转至识别历史页面
        uni.navigateTo({
          url: "/pages/community/community?type=record&title=识别历史",
        });
      }
    },
    // 点击弹出框选项
    onActionSheetSelect(event) {
      console.log("action sheet select", event.detail);
      if (event.detail.name === "拍摄") {
        uni.chooseMedia({
          count: 1,
          mediaType: ["image"],
          sourceType: ["camera"],
          maxDuration: 30,
          camera: "back",
          success: (res) => {
            console.log("选择照片", res.tempFiles);
            this.uploadImage(res.tempFiles[0]);
          },
        });
      } else if (event.detail.name === "相册") {
        uni.chooseMedia({
          count: 1,
          mediaType: ["image"],
          sourceType: ["album"],
          maxDuration: 30,
          success: (res) => {
            console.log("选择照片", res.tempFiles);
            this.uploadImage(res.tempFiles[0]);
          },
        });
      } else if (event.detail.name === "写入记录") {
        this.toNFCTool("write");
      } else if (event.detail.name === "读取记录") {
        this.toNFCTool("read");
      }
    },
    closeActionSheet() {
      this.showActionSheet = false;
    },
    // 上传图片
    async uploadImage(event) {
      // 清空原数据
      this.fileList = [];
      console.log("上传识别图片", event);

      this.fileList.push({
        url: event.tempFilePath,
      });

      console.log("fileList", this.fileList);
      if (this.fileList.length > 0) {
        uni.showLoading({
          title: "上传中",
          mask: false,
        });
        let { data: res } = await uni.uploadFile({
          url: globalParams.uploadUrl,
          filePath: this.fileList[0].url,
          name: "file",
          header: {
            "Content-Type": "multipart/form-data",
          },
        });
        let result = JSON.parse(res);
        console.log("上传图片返回结果", result);
        if (result.code === 200) {
          uni.hideLoading();
          uni.showToast({
            title: "上传成功",
            icon: "none",
          });
          this.imgData = result.data;
          console.log("上传图片返回数据", this.imgData);
          this._recognize();
        } else {
          uni.hideLoading();
          uni.showToast({
            title: "上传失败",
            icon: "none",
          });
        }
      }
    },

    // 识别图片
    async _recognize() {
      uni.showLoading({
        title: "识别中",
        mask: true,
      });
      let { data: res } = await recognize(
        globalParams.baseUrl + this.imgData.path
      );
      console.log("识别结果", res);
      if (res.code === 200 && res.data.result === "识别成功") {
        uni.hideLoading();
        uni.showToast({
          title: "识别成功",
          icon: "none",
          mask: true,
        });
        this.setRecognizeData(null);
        let recognizeFullData = {
          ...res.data,
          imgUrl: globalParams.baseUrl + this.imgData.path,
        };
        // 保存识别数据
        this.setRecognizeData(recognizeFullData);
        console.log("识别数据", this.recognizeData);
        // 保存信息至植物表
        this.saveRecognizeInfo();
        // 识别成功后根据识别结果跳转;
        if (res.data.accuracy > 0.7) {
          uni.navigateTo({
            url: "/pages/result/result?type=recognize&result=success",
          });
        } else {
          uni.navigateTo({
            url: "/pages/result/result?type=recognize&result=fail",
          });
        }
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "识别失败",
          icon: "none",
          mask: true,
        });
        // 识别失败
        uni.navigateTo({
          url: "/pages/result/result?type=recognize&result=fail",
        });
      }
    },
    // 保存信息至植物表
    async saveRecognizeInfo() {
      let { data: res } = await addPlant({
        name: this.recognizeData.name,
        imgUrl: this.imgData.path,
        note: this.recognizeData.accuracy,
      });
      console.log("保存植物信息", res);
      if (res.code === 200) {
        this.saveRecognizeRecord(res.data.id);
      }
    },

    // 保存识别记录
    async saveRecognizeRecord(plantId) {
      let { data: res } = await addRecognizeRecord({
        userId: this.userInfo.id,
        plantId: plantId,
      });
      console.log("保存识别记录", res);
    },

    // NFC读写
    toNFCTool(type) {
      uni.navigateTo({ url: "/pages/NFCTool/NFCTool?type=" + type });
    },
  },
};
</script>

<style lang="scss" scoped>
.features {
  display: flex;
  flex-direction: column;
}
.item {
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 24px;
  font-weight: bold;
  background-color: #ffffff;
  box-shadow: 0px 4px 16px 0px #edeef0;
  margin: 16px 16px 0 16px;
  border-radius: 12px;
  padding: 16px;

  image {
    width: 80px;
    height: 80px;
  }

  &:active {
    background-color: #f2f2f2;
  }
}
</style>
